package com.sc.ktapplication.common.util

import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.sc.ktapplication.R
import java.util.regex.Pattern

object StatusBarUtil {
    private const val KEY_VERSION_OPPO = "ro.build.version.opporom" //OPPO
    private const val KEY_VERSION_MIUI = "ro.miui.ui.version.name" //小米
    private const val KEY_VERSION_EMUI = "ro.build.version.emui" //华为
    private const val KEY_VERSION_SMARTISAN = "ro.smartisan.version" //锤子
    private const val KEY_VERSION_VIVO = "ro.vivo.os.version" //vivo

    /**
     * 设置状态栏透明度、背景颜色、文字颜色
     * @param isTranslate 是否透明，若为true，则bgColor设置无效
     * @param isDarkText  字体颜色，只有黑白两色，无论什么色值，都只会转为黑白两色
     * @param bgColor     背景色，即状态栏颜色，isTranslate若为true则此值无效
     */
    fun setStatusColor(
        activity: Activity,
        isTranslate: Boolean,
        isDarkText: Boolean,
        @ColorRes bgColor: Int
    ) {
        //如果系统为6.0及以上，就可以使用Google自带的方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val window = activity.window
            val decorView = window.decorView
            //可有可无
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            decorView.systemUiVisibility =
                (if (isTranslate) View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN else 0) or if (isDarkText) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
            window.statusBarColor = if (isTranslate) Color.TRANSPARENT else ContextCompat.getColor(
                activity,
                bgColor
            )
        } else { //如果不是6.0及以上则分情况适配
            if (isColorOS_3) { //如果是OPPO Color3.0 & Android 5.1
                //控制字体颜色，只有黑白两色
                val SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT =
                    if (isDarkText) 0x00000010 else 0x00190000
                val window = activity.window
                val decorView = window.decorView
                decorView.systemUiVisibility =
                    (if (isTranslate) View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN else 0) or SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT
                //可有可无
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor =
                    if (isTranslate) Color.TRANSPARENT else ContextCompat.getColor(
                        activity,
                        bgColor
                    )
            } else if (isMIUI6Later) { //如果是Android 6.0以下，MIUI6及以上
                setMIUI6Translate(activity, isTranslate)
                setMIUI6StatusBarDarkMode(activity, isDarkText)
            } else if (isFlyme4Later) {
                darModeForFlyme4(activity, isDarkText)
                if (isTranslate) {
                    setStatusTranslate(activity)
                }
            } else {
                //其他品牌
                if (isTranslate) {
                    setStatusTranslate(activity)
                }
                setStatusBarColor(activity, R.color.light_blue)
            }
        }
    }

    /**
     * 是否是MIUI6及以后版本
     * @return 是否是MIUI6
     */
    private val isMIUI6Later: Boolean
        private get() = try {
            val cla = Class.forName("android.os.SystemProperties")
            val mtd = cla.getMethod("get", String::class.java)
            var `val` =
                mtd.invoke(null, KEY_VERSION_MIUI) as String
            `val` = `val`.replace("[vV]".toRegex(), "")
            val version = `val`.toInt()
            version >= 6
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }

    /**
     * 设置MIUI6及以上状态栏透明,字体为默认白色，Android6.0以上也可以
     * @param on 是否为透明
     */
    private fun setMIUI6Translate(activity: Activity, on: Boolean) {
        val win = activity.window
        val winParams = win.attributes
        val bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
        if (on) {
            winParams.flags = winParams.flags or bits
        } else {
            winParams.flags = winParams.flags and bits.inv()
        }
        win.attributes = winParams
    }

    /**
     * 设置MIUI6及以上，Android6.0以下版本状态栏黑色字符
     * Android 6.0以上此方法无效
     * 此方法是官方给的，应该没有错，我没有MIUI6的手机，无法测试
     */
    private fun setMIUI6StatusBarDarkMode(
        activity: Activity,
        darkmode: Boolean
    ) {
        val clazz: Class<out Window> = activity.window.javaClass
        try {
            var darkModeFlag = 0
            val layoutParams =
                Class.forName("android.view.MiuiWindowManager\$LayoutParams")
            val field =
                layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
            darkModeFlag = field.getInt(layoutParams)
            val extraFlagField = clazz.getMethod(
                "setExtraFlags",
                Int::class.javaPrimitiveType,
                Int::class.javaPrimitiveType
            )
            extraFlagField.invoke(
                activity.window,
                if (darkmode) darkModeFlag else 0,
                darkModeFlag
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 是否是ColorOS_3.0系统 Android 5.1
     * @return 是否是colorOS_3.0
     */
    private val isColorOS_3: Boolean
        private get() = try {
            val cla = Class.forName("android.os.SystemProperties")
            val mtd = cla.getMethod("get", String::class.java)
            var `val` =
                mtd.invoke(null, KEY_VERSION_OPPO) as String
            `val` = `val`.replace("[vV]".toRegex(), "")
            `val` = `val`.substring(0, 1)
            val version = `val`.toInt()
            version >= 3
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }

    /**
     * 判断是否是魅族Flyme4
     * @return 是否是魅族Flyme4
     */
    private val isFlyme4Later: Boolean
        private get() = if ("MEIZU" == Build.BRAND.trim { it <= ' ' }.toUpperCase()) {
            Build.FINGERPRINT.contains("Flyme_OS_4") || Build.VERSION.INCREMENTAL.contains("Flyme_OS_4") || Pattern.compile(
                "Flyme_OS_[4|5]",
                Pattern.CASE_INSENSITIVE
            )
                .matcher(Build.DISPLAY).find()
        } else false

    /**
     * 设置魅族Flyme4以后 状态栏黑色字体
     * 没有手机，从网上找的方法，应该没问题
     * @param dark 是否黑色
     */
    private fun darModeForFlyme4(activity: Activity, dark: Boolean) {
        val result = false
        try {
            val e = activity.window.attributes
            val darkFlag =
                WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
            val meizuFlags =
                WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags")
            darkFlag.isAccessible = true
            meizuFlags.isAccessible = true
            val bit = darkFlag.getInt(null)
            var value = meizuFlags.getInt(e)
            value = if (dark) {
                value or bit
            } else {
                value and bit.inv()
            }
            meizuFlags.setInt(e, value)
            activity.window.attributes = e
        } catch (var8: Exception) {
            Log.e("StatusBar", "darkIcon: failed")
        }
    }

    /**
     * 设置状态栏背景颜色，不适配5.0以下系统
     * @param color 颜色值
     */
    fun setStatusBarColor(activity: Activity, color: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.window.statusBarColor = activity.resources.getColor(color)
        }
    }

    /**
     * 使状态栏透明
     *
     *
     * 适用于图片作为背景的界面,此时需要图片填充到状态栏
     *
     * @param activity 需要设置的activity
     */
    fun setTranslucent(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 设置状态栏透明
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            // 设置根布局的参数
            val rootView =
                (activity.findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(
                    0
                ) as ViewGroup
            rootView.fitsSystemWindows = true
            rootView.clipToPadding = true
        }
    }

    /**
     * 设置状态栏透明，Android4.4、Android5.0以上方法不一
     * 我感觉5.0以下的系统已经很少了吧，应该不需要适配了吧
     * 如果只是设置状态栏透明，就使用这个就好了
     */
    fun setStatusTranslate(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val decorView = activity.window.decorView
            decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            activity.window.statusBarColor = Color.TRANSPARENT
        } else {
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
    }
}